<template>
  <div class="project">
    <div class="project-search">
      <el-form class="search-form" ref="formRef" label-suffix=" :" :model="projectListParams">
        <div class="search-list">
          <el-form-item label="排序">
            <el-select v-model="projectListParams.sortStr" placeholder="请选择" clearable filterable>
              <el-option v-for="item in sortEnum" :key="item.name" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="分类">
            <el-select v-model="projectListParams.typeId" placeholder="请选择" clearable filterable>
              <el-option v-for="item in getDict('questionId')" :key="item.name" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="标题">
            <el-input v-model="projectListParams.searchKey" placeholder="请填写" clearable></el-input>
          </el-form-item>
        </div>
        <div class="operation">
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="search"> 搜索 </el-button>
            <el-button :icon="Refresh" @click="reset(formRef)"> 重置 </el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="project-content project-content-options">
      <div class="content-top">
        <el-button v-auth="'add'" type="primary" :icon="Plus" @click="add"> 新增 </el-button>
        <el-button :icon="Refresh" circle @click="refresh" />
      </div>
    </div>
    <div class="project-content">
      <div class="cot-list-wrap">
        <el-scrollbar>
          <PullLoad
            :class-name="'cot-list'"
            :style="`--gap: 20px ${gap}px`"
            v-model:params="projectListParams"
            :api="getQuestionByMobile"
            v-model:value="projectList"
          >
            <div class="list-item li" v-for="(item, index) in projectList" :key="index" @click="jump(item.id)">
              <div class="tit-part">
                <p class="tit sle break-word">{{ item.title }}</p>
                <p class="content mle break-word">{{ item.content }}</p>
                <p class="info">
                  <span>
                    <i><img :src="$urlResource + item.avatarUrl" alt="" /></i>
                    <i>{{ item.userName }}</i>
                  </span>
                  <span>
                    <i> <SvgIcon name="preview" /></i>
                    <i>{{ item.viewNumber }}</i>
                  </span>
                  <span>
                    <i> <SvgIcon name="time" /></i>
                    <i>{{ item.gmtCreate || item.gmtModified }}</i>
                  </span>
                  <span class="btn">{{ getDictItem("questionId", item.typeId) }}</span>
                  <span>
                    <i v-if="item.reward"><SvgIcon name="jb" /></i>
                    <i v-if="item.reward">{{ item.reward }}</i>
                  </span>
                </p>
              </div>
              <div class="img-part ml20">
                <template v-if="item.questionImg.length">
                  <img
                    v-for="(itm, idx) in item.questionImg.slice(0, 3)"
                    :src="$urlResource + itm.path"
                    alt=""
                    :key="itm.path + '_' + idx"
                  />
                </template>
              </div>
              <div @click.stop class="ml20 ddwz" v-if="isEdit(item)">
                <el-dropdown trigger="click">
                  <span class="el-dropdown-link">
                    <div class="tit-right">...</div>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="edit(item)">编辑 </el-dropdown-item>
                      <el-dropdown-item @click="deleteComment(item)">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </PullLoad>
          <el-empty :image-size="200" v-if="!projectList.length" description="暂无项目" />
        </el-scrollbar>
      </div>
      <Dialog v-if="drawerVisible" v-model:drawerVisible="drawerVisible" v-model:config="config" @change="refresh" />
    </div>
  </div>
</template>
<script lang="ts" setup>
import { Search, Plus, Refresh } from "@element-plus/icons-vue";
import { ref, onMounted, onBeforeUnmount, computed, inject } from "vue";
import { Project } from "@/api/interface/project";
import { useRouter } from "vue-router";
import { useDict } from "@/hooks/useDict";
import type { FormInstance } from "element-plus";
import { getQuestionByMobile, publishQuestion, updateQuestion, deleteQuestion } from "@/api/modules/sys";
import PullLoad from "@/components/PullLoad/index.vue";
import Dialog from "@/components/DialogForm/index.vue";
import { QA } from "@/constants";
import { useUserStore } from "@/stores/modules/user";
import { useHandleData } from "@/hooks/useHandleData";
/**hook */
const { getDict, getDictItem, getDictAsync } = useDict(["questionId"]);
/**变量 */
const urlResource = inject("urlResource") as any;
const userStore = useUserStore();
const formRef = ref<FormInstance>();
const sortEnum = ref([
  {
    value: "reward",
    label: "按悬赏"
  },
  {
    value: "gmt_create",
    label: "按发布时间"
  },
  {
    value: "view_number",
    label: "按浏览量"
  }
]);
let drawerVisible = ref(false);
let config = ref<any>({ width: 60 });
let gap = ref(20);
let projectListParams = ref({
  currentPage: 1,
  pageSize: 30,
  searchKey: "",
  typeId: "",
  status: undefined,
  sortStr: "",
  redisKey: undefined
});
let projectList: Project.ResProjectData = ref([]);
const router = useRouter();

// computed
const isEdit = computed(() => {
  return (question: any) => userStore.userInfo.id === question.userId;
});
/** 方法 */
const reset = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  projectListParams.value = {
    currentPage: 1,
    pageSize: 30,
    searchKey: "",
    typeId: "",
    status: undefined,
    sortStr: "",
    redisKey: undefined
  };
  refresh();
};
const search = function () {
  projectListParams.value.currentPage = 1;
  getQuestionByMobileFn();
};
const jump = id => {
  router.push("/questionList/detail?id=" + id);
};
// const objResizeObserver = new ResizeObserver(function (entries) {
//   const entry = entries[0];
//   const cr = entry.contentRect;
//   const num = Math.floor(cr.width / 540);
//   gap.value = (cr.width - num * 540) / (num - 1);
// });
const getQuestionByMobileFn = async () => {
  try {
    const { data } = await getQuestionByMobile(projectListParams.value);
    projectList.value = data.records || [];
  } catch (error) {
    console.log(error);
  }
};

// 新增
const add = async () => {
  config.value.message = "添加成功";
  drawerVisible.value = true;
  config.value.title = "新增提问";
  config.value.form = {
    formData: {
      title: "",
      content: "",
      typeId: "",
      reward: undefined,
      questionImg: []
    },
    rules: {
      typeId: [{ required: true, message: "请选择问题类型" }],
      title: [{ required: true, message: "请填写问题标题" }],
      content: [{ required: true, message: "请填写问题内容" }],
      questionImg: [{ required: true, message: "请上传问题图片" }]
    }
  };
  let { data } = await getDictAsync("questionId");
  config.value.column = [
    {
      type: "group",
      title: "",
      direction: "",
      list: [
        {
          type: "select",
          key: "typeId",
          formItemAttribute: {
            label: "问题类型"
          },
          attributes: {
            placeholder: "请选择问题类型",
            options: data,
            multiple: false,
            filterable: true,
            clearable: true
          }
        },
        {
          type: "inputNumber",
          key: "reward",
          formItemAttribute: {
            label: "悬赏金额"
          },
          attributes: {
            placeholder: "请填写悬赏金额",
            controls: false
          }
        }
      ]
    },
    {
      type: "input",
      key: "title",
      formItemAttribute: {
        label: "标题"
      },
      attributes: {
        placeholder: "请填写标题内容"
      }
    },
    {
      type: "input",
      key: "content",
      formItemAttribute: {
        label: "问题详情"
      },
      attributes: {
        placeholder: "请填写问题详情",
        type: "textarea",
        rows: 5
      }
    },
    {
      type: "file",
      key: "questionImg",
      formItemAttribute: {
        label: "问题图片"
      },
      attributes: {
        "prefix-data": QA,
        multiple: true,
        showFileList: true,
        limit: 30,
        width: "140px",
        height: "140px",
        type: "image",
        listType: "picture-card",
        fileType: ["image/jpeg", "image/png", "image/gif"]
      }
    }
  ];
  config.value.api = publishQuestion;
  config.value.transformData = data => {
    data.questionImg = data.questionImg.map(item => {
      return {
        name: item.name,
        originalName: item.originalName,
        path: item.path
      };
    });
    return data;
  };
};

// 编辑
const edit = async (initData: any) => {
  initData = JSON.parse(JSON.stringify(initData));
  // 处理图片默认值
  initData.questionImg = initData.questionImg.map((item: any) => {
    item.url = urlResource + item.path;
    return item;
  });
  config.value.message = "编辑成功";
  drawerVisible.value = true;
  config.value.title = "编辑提问";
  config.value.form = {
    formData: {
      id: initData.id,
      title: initData.title,
      content: initData.content,
      typeId: initData.typeId,
      reward: undefined,
      questionImg: initData.questionImg
    },
    rules: {
      typeId: [{ required: true, message: "请选择问题类型" }],
      title: [{ required: true, message: "请填写问题标题" }],
      content: [{ required: true, message: "请填写问题内容" }],
      questionImg: [{ required: true, message: "请上传问题图片" }]
    }
  };
  let { data } = await getDictAsync("questionId");
  config.value.column = [
    {
      type: "group",
      title: "",
      direction: "",
      list: [
        {
          type: "select",
          key: "typeId",
          formItemAttribute: {
            label: "问题类型"
          },
          attributes: {
            placeholder: "请选择问题类型",
            options: data,
            multiple: false,
            filterable: true,
            clearable: true
          }
        },
        {
          type: "inputNumber",
          key: "reward",
          formItemAttribute: {
            label: "悬赏金额"
          },
          attributes: {
            placeholder: "请填写悬赏金额",
            controls: false,
            disabled: true
          }
        }
      ]
    },
    {
      type: "input",
      key: "title",
      formItemAttribute: {
        label: "标题"
      },
      attributes: {
        placeholder: "请填写标题内容"
      }
    },
    {
      type: "input",
      key: "content",
      formItemAttribute: {
        label: "问题详情"
      },
      attributes: {
        placeholder: "请填写问题详情",
        type: "textarea",
        rows: 5
      }
    },
    {
      type: "file",
      key: "questionImg",
      formItemAttribute: {
        label: "问题图片"
      },
      attributes: {
        "prefix-data": QA,
        multiple: true,
        showFileList: true,
        limit: 30,
        width: "140px",
        height: "140px",
        type: "image",
        listType: "picture-card",
        fileType: ["image/jpeg", "image/png", "image/gif"]
      }
    }
  ];
  config.value.api = updateQuestion;
  config.value.transformData = data => {
    data.questionImg = data.questionImg.map(item => {
      return {
        name: item.name,
        originalName: item.originalName,
        path: item.path
      };
    });
    return data;
  };
};

// 删除
const deleteComment = async (option: any) => {
  const { id } = option;
  await useHandleData(deleteQuestion, { id }, `删除提问`);
  refresh();
};
const refresh = () => {
  getQuestionByMobileFn();
};
onBeforeUnmount(() => {
  // objResizeObserver.unobserve(listWrapRef.value);
});
onMounted(() => {
  // 观察文本域元素
  // objResizeObserver.observe();
  getQuestionByMobileFn();
});
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
